<!--
 * @Author: 噜噜雯雯 2199987619@qq.com
 * @Date: 2025-05-27 08:43:07
 * @LastEditors: 噜噜雯雯 2199987619@qq.com
 * @LastEditTime: 2025-09-28 10:13:36
 * @FilePath: \linePatrol\vue-element-plus-admin\src\views\Authorization\User\components\Write.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<script setup lang="tsx">
import { Form, FormSchema } from '@/components/Form'
import { useForm } from '@/hooks/web/useForm'
import { PropType, reactive, ref, watch } from 'vue'
import { UserListAlltype } from '@/api/department/types'
import { useValidator } from '@/hooks/web/useValidator'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import { Icon } from '@/components/Icon'
const { required } = useValidator()
const userStore = useUserStore()
const props = defineProps({
  currentRow: {
    type: Object as PropType<UserListAlltype>,
    default: () => {}
  },
  formSchema: {
    type: Array as PropType<FormSchema[]>,
    default: () => []
  },
  UserDetail: {
    type: Object as PropType<any>,
    default: () => undefined
  }
})

const imageUrl = ref('')
const NewCurrentRow: any = [
  {
    field: 'roleIds',
    label: '角色',
    component: 'Select',
    colProps: {
      span: 15
    },
    componentProps: {
      multiple: true,
      options: props.UserDetail.roles.map((item) => {
        console.log(item.roleName, item.roleId)
        return {
          label: item.roleName,
          value: item.roleId
        }
      })
    }
  },
  {
    field: 'postIds',
    label: '岗位',
    component: 'Select',
    componentProps: {
      multiple: true,
      options: props.UserDetail.posts.map((item) => {
        console.log(item.postName, item.postId)
        return {
          label: item.postName,
          value: item.postId
        }
      })
    },
    colProps: {
      span: 15
    }
  },
  {
    field: 'Img',
    label: '更改头像',
    component: 'Upload',
    showFileList: false,
    componentProps: {
      showFileList: false,
      action: '/api/file/upload',
      listType: 'picture-card',
      headers: { Authorization: userStore.getToken },
      onSuccess: (_response, uploadFile) => {
        imageUrl.value = URL.createObjectURL(uploadFile.raw!)
      },
      beforeUpload: (rawFile) => {
        if (rawFile.type !== 'image/jpeg') {
          ElMessage.error('请正确提交JPG格式图片!')
          return false
        } else if (rawFile.size / 1024 / 1024 > 2) {
          ElMessage.error('图片大小不得超过2MB!')
          return false
        }
        return true
      },
      slots: {
        default: () => (
          <>
            {imageUrl.value ? <img src={imageUrl.value} class="avatar" /> : null}
            {!imageUrl.value ? <Icon icon="ep:plus" size={18} /> : null}
          </>
        )
      }
    }
  }
]
const localFormSchema = ref(JSON.parse(JSON.stringify(props.formSchema)))
if (props.currentRow == null) {
  localFormSchema.value[2].hidden = false
  console.log('添加')
} else {
  localFormSchema.value[2].hidden = true
}

const Data = [...localFormSchema.value, ...NewCurrentRow]
const rules = reactive({
  userName: [required()],
  nickName: [required()],
  status: [required()],
  roleIds: [required()],
  postIds: [required()],
  password: [required()],
  deptId: [required()]
})

const { formRegister, formMethods } = useForm()
const { setValues, getFormData, getElFormExpose } = formMethods
const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log(err)
  })
  if (valid) {
    const formData = await getFormData()
    if (formData.Img) {
      formData.avatar = formData.Img[0].response.data.url
    }
    return formData
  }
}

watch(
  () => props.currentRow,
  (currentRow) => {
    if (!currentRow) return
    setValues(currentRow)
  },
  {
    deep: true,
    immediate: true
  }
)

defineExpose({
  submit
})
</script>

<template>
  <Form :rules="rules" @register="formRegister" :schema="Data" />
</template>
<style scoped>
:deep(.avatar) {
  width: 100% !important;
}
:deep(.el-icon.avatar-uploader-icon) {
  width: 70px;
  height: 70px;
  font-size: 20px;
  color: #8c939d;
  text-align: center;
}
:deep(.el-upload) {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}

:deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}
</style>
